<template>
  <div class="dashboard-editor-container">
    <div class="chart-wrapper1">
      <el-card>
        <el-form
          :model="seatForm"
          style="margin-top:10px;"
          size="mini"
          label-position="top"
          ref="seatForm"
        >
          <el-row :gutter="10">
            <el-col :lg="6" :md="6">
              <el-form-item label="多媒体类型" prop="channel">
                <el-select v-model="seatForm.channel" disabled placeholder="请选择渠道类型">
                  <el-option
                    v-for="item in channelOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="4" :md="6">
              <el-form-item label="班" prop="company">
                <el-select v-model="seatForm.company" placeholder="请选择班" @change="queryTeam">
                  <el-option key="index" label="全部" value></el-option>
                  <el-option
                    v-for="item in companyList"
                    :key="item.TEAMID"
                    :label="(item.TEAMID+'-'+item.TEAMNAME)"
                    :value="item.TEAMID"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :lg="4">
              <el-form-item label="组" prop="team">
                <el-select
                  v-model="seatForm.team"
                  filterable
                  placeholder="请选择组"
                  @change="agentQuery"
                >
                  <el-option key="index" label="全部" value></el-option>
                  <el-option
                    v-for="item in teamList"
                    :key="item.TEAMID"
                    :label="(item.TEAMID+'-'+item.TEAMNAME)"
                    :value="item.TEAMID"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :md="6" :lg="5">
              <el-form-item label="坐席" prop="agent">
                <el-select v-model="seatForm.agent" multiple collapse-tags placeholder="请选择坐席">
                  <el-option
                    v-for="item in agentOptions"
                    :key="item.AGENTID"
                    :label="item.AGENTNAME"
                    :value="item.AGENTID"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="12" :md="12" class="searchBtnMarginTop">
              <el-button
                type="primary"
                icon="el-icon-search"
                :loading="loading"
                size="mini"
                @click="querySeat"
              >查询</el-button>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-refresh"
                @click="clearForm('seatForm')"
              >重置</el-button>
              <el-button
                type="success"
                size="mini"
                icon="el-icon-download"
                @click="downloadTemplate"
              >导出报表</el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <el-row style="margin-top:20px">
      <el-col class="total-col">
        <el-card>
          <div slot="header" class="clearfix">
            <el-col>
              <el-button style="float: left; padding: 3px 0" type="text" @click="openRank">坐席状态排名设置</el-button>
            </el-col>
          </div>
          <el-table :data="tableData">
            <el-table-column prop="ID" label="坐席工号" width="100" align="center"></el-table-column>
            <el-table-column prop="agentName" label="坐席姓名" width="120" align="center"></el-table-column>
            <el-table-column
              prop="currentStatus"
              label="当前状态"
              align="center"
              :formatter="dataFormat"
            ></el-table-column>
            <el-table-column prop="duration" label="当前状态持续时间" align="center" width="135"></el-table-column>
            <el-table-column prop="logincount" label="签入次数" align="center"></el-table-column>
            <el-table-column prop="logindurn" label="签入时长" align="center" width="130">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row.logindurn)}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypecount" label="小休次数" align="center"></el-table-column>
            <el-table-column prop="breaktypedurn" label="小休时长" align="center">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row.breaktypedurn)}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" label="通话次数" align="center">
              <template slot-scope="scope">
                <div>{{scope.row['通话次数']}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" align="center" width="110" label="通话时长">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row['通话时长'])}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" align="center" width="110" label="空闲时长">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row['空闲时长'])}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" align="center" width="110" label="通话均长">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row['通话均长'])}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" width="100" label="工时利用率">
              <template slot-scope="scope">
                <div>{{keepTwoDecimal(scope.row['工时利用率']*100)+ '%'}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="breaktypedurn" width="110" label="平均振铃时长">
              <template slot-scope="scope">
                <div>{{secondFormat(scope.row['平均振铃时长'])}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="VIDEO_ANSWER20COUNT" label="视频20S接通量" align="center">
              <template slot-scope="scope">
                <div>{{scope.row['answer20count']}}</div>
              </template>
              </el-table-column>
            <el-table-column prop="VIDEO_20SERVICELEVEL" label="视频20S服务水平" align="center">
              <template slot-scope="scope">
                <div>{{keepTwoDecimal(scope.row['20S服务水平']*100)+ '%'}}</div>
              </template>
            </el-table-column>
            <!-- <el-table-column :prop="seatForm.channel" :label="seatForm.channel" align="center">
              <el-table-column prop="breaktypedurn" label="通话次数" align="center">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{scope.row[seatForm.channel][0]['通话次数']}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <el-table-column prop="breaktypedurn" align="center" width="110" label="通话时长">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{secondFormat(scope.row[seatForm.channel][0]['通话时长'])}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <el-table-column prop="breaktypedurn" align="center"  width="110" label="空闲时长">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{secondFormat(scope.row[seatForm.channel][0]['空闲时长'])}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <el-table-column prop="breaktypedurn" align="center" width="110" label="通话均长">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{secondFormat(scope.row[seatForm.channel][0]['通话均长'])}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <el-table-column prop="breaktypedurn" width="100" label="工时利用率">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{scope.row[seatForm.channel][0]['工时利用率']}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
              <el-table-column prop="breaktypedurn" width="110" label="平均振铃时长">
                <template slot-scope="scope">
                  <div v-if="scope.row[seatForm.channel].length!=0">
                    {{secondFormat(scope.row.video[0]['平均振铃时长'])}}
                  </div>
                  <div v-else></div>
                </template>
              </el-table-column>
            </el-table-column>-->
          </el-table>
          <el-dialog
            title="排名设置"
            :visible.sync="rankIsShow"
            :close-on-click-modal="false"
            width="45%"
            @close="closeDialog"
          >
            <el-alert title="以下各项的值总和必须等于1" type="warning" style="margin-bottom:20px;" show-icon></el-alert>
            <el-form
              :model="SORTRULE"
              :rules="rules"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="签入次数" prop="logincount">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.logincount"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="签入时长" prop="logindurn">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.logindurn"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="小休次数" prop="breaktypecount">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.breaktypecount"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="小休时长" prop="breaktypedurn">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.breaktypedurn"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="通话次数" prop="establishedcount">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.establishedcount"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="通话时长" prop="establisheddurn">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.establisheddurn"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="空闲时长" prop="readydurn">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE.readydurn"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="通话均长" prop="'通话均长'">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE['通话均长']"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工时利用率" prop="'工时利用率'">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE['工时利用率']"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="平均振铃时长" prop="'平均振铃时长'">
                    <el-input-number
                      :precision="1"
                      :step="0.1"
                      :max="1"
                      :min="0"
                      size="small"
                      v-model="SORTRULE['平均振铃时长']"
                    ></el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="24" :offset="5">
                  <el-form-item>
                    <el-button type="primary" size="small" @click="onSubmit">确认</el-button>
                    <el-button size="small" @click="reset">取消</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import toolBox from "@/common/utils/toolBox";
// import siteTendency from "./dialog/siteTendency";
// import targetValMain from "./dialog/targetValMain";
import agentDetail from "@/message/siteManagement/agentDetail/agentDetail";
// 发送接口
import requestYg from "@/common/utils/requestYg";
//六维指标查询
import request from "@/common/utils/requestWFM";
// 班组接口
import teamManage from "@/message/seat-manage/setaTeam/teamManage";
// 坐席维护接口
import agentManage from "@/message/seat-manage/SeatInfoManage/agentManage";
import getGlobalParams from "@/common/utils/getGlobalParams";

export default {
  name: "",
  data() {
    return {
      SORTRULE: {
        logincount: 0.1,
        logindurn: 0.1,
        breaktypecount: 0.1,
        breaktypedurn: 0.1,
        establishedcount: 0.1,
        establisheddurn: 0.1,
        readydurn: 0.1,
        通话均长: 0.1,
        工时利用率: 0.1,
        平均振铃时长: 0.1
      },
      fileUrl: getGlobalParams.get("FileDownloadAddress"),
      rules: {},
      rankIsShow: false,
      agentOptions: [],
      tableData: [],
      channelOption: [
        {
          value: "video",
          label: "视频"
        },
        {
          value: "voice",
          label: "电话"
        },
        {
          value: "chat",
          label: "文字"
        }
      ],
      seatForm: {
        channel: "video",
        company: "",
        team: "",
        agent: []
      },
      teamList: [],
      companyList: [],
      dictionaryOption: [],
      loading: false
    };
  },
  computed: {},
  created() {},
  mounted() {
    this.agentQuery();
    // this.querySeat()
    this.queryClass();
  },
  watch: {},
  methods: {
    // 秒格式化
    secondFormat(value) {
      if (value == undefined) {
        return "";
      }
      return toolBox.formatSeconds(value);
    },
    //保留两位小数（四舍五入）
    keepTwoDecimal(value){
      if (value == undefined) {
        return "";
      }
      return toolBox.keepTwoDecimal(value);
    },
    // 毫秒格式化
    timeFormat(mss) {
      if (mss == undefined) {
        return "";
      }
      if (mss == 0) {
        return 0;
      }
      if (mss < 1) {
        return mss + "秒";
      }
      let result = parseInt(mss)
      // var days = parseInt(mss / (1000 * 60 * 60 * 24));
      let h = Math.floor((result % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)) == 0 ? ''  : Math.floor((result % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      let m = Math.floor((result % (1000 * 60 * 60)) / (1000 * 60)) == 0 ? '' : Math.floor((result % (1000 * 60 * 60)) / (1000 * 60));
      let s = Math.floor((result % (1000 * 60)) / 1000) == 0 ? '' : Math.floor((result % (1000 * 60)) / 1000);
      let hour = h == 0 ?'':'时'
      let min = m ==0 ?'':'分'
      let sec = s == 0?'':'秒'
    
      result = `${h}${hour}${m}${min}${s}${sec}`
      return result;
    },
    closeDialog() {
      this.SORTRULE = {
        logincount: 0.1,
        logindurn: 0.1,
        breaktypecount: 0.1,
        breaktypedurn: 0.1,
        establishedcount: 0.1,
        establisheddurn: 0.1,
        readydurn: 0.1,
        通话均长: 0.1,
        工时利用率: 0.1,
        平均振铃时长: 0.1
      };
    },
    reset() {
      this.rankIsShow = false;
      this.SORTRULE = {
        logincount: 0.1,
        logindurn: 0.1,
        breaktypecount: 0.1,
        breaktypedurn: 0.1,
        establishedcount: 0.1,
        establisheddurn: 0.1,
        readydurn: 0.1,
        通话均长: 0.1,
        工时利用率: 0.1,
        平均振铃时长: 0.1
      };
    },
    onSubmit() {
      let sum = 0;
      for (var key in this.SORTRULE) {
        if (this.SORTRULE[key] == undefined) this.SORTRULE[key] = 0;
        sum += Number(this.SORTRULE[key].toFixed(1));
      }
      if (sum.toFixed(1) != 1) {
        this.$message.error("以上各项的值总和必须等于1");
        return false;
      }
      this.querySeat();
      this.rankIsShow = false;
    },
    // 打开现场排名设置
    openRank() {
      this.rankIsShow = true;
    },
    // 查询坐席
    async agentQuery() {
      let resBody = new agentManage();
      resBody.data.OPERATION = "5";
      resBody.data.AGENTCLASS = this.seatForm.company;
      resBody.data.AGENTTEAM = this.seatForm.team;
      // resBody.data.PAGEFLAG = 4;
      // resBody.data.PAGEFLAG = '5';
      // resBody.data.PAGEROWNUM = 1000
      // resBody.data.CURRPAGE = 1
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.agentOptions = response.RSP_BODY.struct;
        this.querySeat();
      } else {
        this.$message({
          type: "error",
          message: "该组下没有关联的坐席"
        });
        // this.seatForm.team = ''
        this.agentOptions = [];
      }
    },
    // 查询班
    async queryClass() {
      let resBody = new teamManage();
      resBody.data.OPERATION = "4";
      resBody.data.TEAMTYPE = "1";
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.companyList = response.RSP_BODY.struct;
      } else {
        this.$message({
          type: "error",
          message:
            "请求失败，错误码:" +
            response.SYS_HEAD.ReturnCode +
            "，错误信息：" +
            response.SYS_HEAD.ReturnMessage
        });
        this.companyList = [];
      }
    },
    // 查询组
    async queryTeam() {
      this.agentOptions = [];
      this.seatForm.team = "";
      if (this.seatForm.company == "") {
        this.seatForm.team = "";
        return;
      }
      let resBody = new teamManage();
      resBody.data.OPERATION = "4";
      resBody.data.TEAMTYPE = "2";
      resBody.data.PAGEFLAG = 4;
      resBody.data.CURRPAGE = 1;
      resBody.data.PAGEROWNUM = 100;
      resBody.data.HTEAMID = this.seatForm.company;
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode === "000000") {
        this.teamList = response.RSP_BODY.struct;
        this.agentQuery();
      } else {
        this.$message({
          type: "error",
          message: "该班下没有对应组"
        });
        this.teamList = [];
        // this.seatForm.team = ''
        this.seatForm.company = "";
      }
    },
    async querySeat() {
      this.tableData = [];
      let resBody = new agentDetail();
      if (this.seatForm.agent.length == 0) {
        this.seatForm.team =
          this.seatForm.company == "" ? "" : this.seatForm.team;
        let agent = [];
        this.agentOptions.forEach(item => {
          agent.push(item.AGENTID);
        });
        resBody.data.ID = agent.join(",");
      } else {
        resBody.data.ID = this.seatForm.agent.join(",");
      }
      resBody.data.SORTRULE = this.SORTRULE;
      resBody.data.CHANNEL = this.seatForm.channel;
      resBody.data.FLAG = "S"; //S为查询，O为导出
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.tableData = response.RSP_BODY.struct;
        console.log("tableData==" + JSON.stringify(this.tableData));
      } else {
        this.$message({
          type: "error",
          message:
            "请求失败，错误码:" +
            response.SYS_HEAD.ReturnCode +
            "，错误信息：" +
            response.SYS_HEAD.ReturnMessage
        });
      }
    },
    // 重置查询条件
    clearForm(item) {
      // 重置表格
      this.$refs["" + item].resetFields();
    },
    // 数据字典
    async dictionaryQuery() {
      let resBody = new dataQuery();
      resBody.data.FIELDCODE = "QUEUEPARA";
      // resBody.data.FIELDNAME = this.form.name;
      resBody.data.CurrPage = 1;
      resBody.data.PageRowNum = 200;
      let response = await request(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        this.dictionaryOption = response.BODY.FIEDATA;
        let arr = response.BODY.FIEDATA;
        arr.forEach(item => {
          this.data.push({
            key: item.FIELDKEY,
            label: item.FIELDVALUE
          });
        });
        this.chooseFormat();
      } else {
        this.$message({
          type: "error",
          message:
            "请求失败，错误码:" +
            response.SYS_HEAD.ReturnCode +
            "，错误信息：" +
            response.SYS_HEAD.ReturnMessage
        });
      }
    },
    // 导出报表
    async downloadTemplate() {
      let resBody = new agentDetail();
      if (this.seatForm.agent.length == 0) {
        this.seatForm.team =
          this.seatForm.company == "" ? "" : this.seatForm.team;
        let agent = [];
        this.agentOptions.forEach(item => {
          agent.push(item.AGENTID);
        });
        resBody.data.ID = agent.join(",");
      } else {
        resBody.data.ID = this.seatForm.agent.join(",");
      }
      resBody.data.SORTRULE = this.SORTRULE;
      resBody.data.CHANNEL = this.seatForm.channel;
      resBody.data.FLAG = "O"; //S为查询，O为导出
      let response = await requestYg(resBody);
      if (response.SYS_HEAD.ReturnCode == "000000") {
        let res = response.RSP_BODY;
        let name = res.FileName;
        let url = res.FilePath;
        this.downloadFile(this.fileUrl + url + "/" + name);
        console.log("路径===" + this.fileUrl + url + "/" + name);
      } else {
        this.$message({
          type: "error",
          message:
            "请求失败，错误码:" +
            response.SYS_HEAD.ReturnCode +
            "，错误信息：" +
            response.SYS_HEAD.ReturnMessage
        });
      }
    },
    dataFormat(row, column) {
      if (column.property == "currentStatus")
        return row[column.property] == "login"
          ? "签入"
          : row[column.property] == "ready"
          ? "就绪"
          : row[column.property] == "matched"
          ? "已匹配"
          : row[column.property] == "ringing"
          ? "振铃"
          : row[column.property] == "answer"
          ? "接听（视频建立）状态"
          : row[column.property] == "established"
          ? "通话中状态"
          : row[column.property] == "release"
          ? "挂断"
          : row[column.property] == "aftercallwork"
          ? "话后小结（整理）"
          : row[column.property] == "notready"
          ? "示忙"
          : row[column.property] == "breaktype"
          ? "小休模式"
          : row[column.property] == "logout"
          ? "签出"
          : row[column.property];
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-table .cell {
  white-space: pre-line;
}

.right-col {
  height: 100%;
  background: #ffffff;
  margin-left: 20px;
  margin-top: 10px;
  // margin-bottom: 20px;
}

.div {
  height: 100%;
  background: #ffffff;
  // margin-top: 10px;
}

.left-col {
  height: 100%;
  background: #ffffff;
  margin-top: 10px;
}

.main1 {
  margin-bottom: 5px;
  height: 650px;
  background: #ffffff;
}

.main {
  margin-bottom: 5px;
  height: 100%;
  background: #f0f2f5;

  .total-col {
    width: 100%;
    // height: 100%;
    background: #ffffff;
  }

  .left-col {
    height: 100%;
    background: #ffffff;
  }

  .right-col {
    height: 100%;
    background: #ffffff;
    margin-left: 20px;
  }

  .el-card {
    height: 100%;
  }

  .linstyel {
    padding-top: 30px;
    height: 100%;
  }

  .main1 {
    height: 40%;
  }

  .main2 {
    height: 40%;
  }

  .class1 {
    margin-left: 20px;
    display: inline-block;
    width: 10px;
    height: 10px;
    //  border: 1px solid #2ca7e9;
    background-color: #2ca7e9;
  }

  .class2 {
    margin-left: 20px;
    display: inline-block;
    width: 10px;
    height: 10px;
    background-color: #19d4ae;
    //  border: 1px solid red;
  }
}

.dashboard-editor-container {
  height: 100%;
  padding: 16px;
  background-color: rgb(240, 242, 245);

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }

  .chart-wrapper1 {
    background: #f5f5f5;
    // padding: 16px 16px 0;
    margin-bottom: 2px;
    color: #2ca7e9;
  }

  .chart-wrapper2 {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;

    height: 100%;
    float: left;
  }

  .a {
    float: right;
  }
}
</style>
